from django.shortcuts import render
from rest_framework.views import APIView
from .models import Area
from rest_framework.response import Response
from .serializers import AreaSerializer, SubsSerializer
from rest_framework import status
from rest_framework.generics import ListAPIView, RetrieveAPIView, GenericAPIView
from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin


# Create your views here.


# class AreaListView(APIView):
#     """
#     查询所有省
#     """
#     def get(self, request):
#         #获取指定的查询集
#         qs = Area.objects.filter(parent=None)
#         #创建序列化器 进行序列化
#         serializer = AreaSerializer(qs, many=True)
#         #响应
#         return Response(serializer.data)
#
#
# class AreaDatailView(APIView):
#     """查询省或市"""
#     def get(self, request, pk):
#         #根据pk 查询指定的省或市
#         try:
#             area = Area.objects.get(id=pk)
#         except Area.DoesNotExist:
#             return Response({'message': '无效pk'}, status=status.HTTP_400_BAD_REQUEST)
#         #创建序列化器 进行序列化
#         serializer = SubSerializer(area)
#         #响应
#         return Response(serializer.data)


# class AreaListView(ListAPIView):
#     """
#     查询所有省
#     """
#     serializer_class = AreaSerializer
#     queryset = Area.objects.filter(parent=None)
#
#
# class AreaDatailView(RetrieveAPIView):
#     """查询省或市"""
#     serializer_class = SubSerializer
#     queryset = Area.objects.all()

# CacheResponseMixin必须要写在ReadOnlyModelViewSet前面，因为CacheResponseMixin重写super调用了ReadOnlyModelViewSet的list方法
class AreaViewSet(CacheResponseMixin, ReadOnlyModelViewSet):

    #指定查询集
    def get_queryset(self):
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

    #指定序列化器

    def get_serializer_class(self):
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubsSerializer






